
import React, { useEffect, useState } from 'react'
import style from './index.module.scss'

import red_envelope_down_second from "./red_envelope_down_second.png"
import red_envelope_up_second from "./red_envelope_up_second.png"
import btn_chai_second from "./btn_chai_second.png"

export default function(props) {
  const [animate,setAnimate]= useState(false)
  const [animateOpening,setAnimateOpening]= useState(false)
  const [imgCount,setImgCount]= useState(0)

  const {detail}= props
  const style_= props.style
  const onLoad_= ()=>{
    setImgCount((imgCount)=>{
      ++imgCount
      if(imgCount >= 3){  //红包各图标加载完成后开启动画效果
        setTimeout(()=>{
          setAnimate(true)
        },Math.random()*1000)
      }
      return imgCount
    })
  }

  const onClick_= ()=>{
    if(!props.isAnimate){
      return props.onClick && props.onClick(props.detail)
    }
    setAnimateOpening(true)
    setTimeout(()=>{
      if(props.onClick){
        props.onClick(props.detail)
      }
    },1000)
  }

  const Package= (animateOpening, onLoad_, onClick_, className_)=>(  //单个红包
      <div className={`${style.opening_box} 
                        ${animateOpening?style.animateOpening
                          :''} 
                        ${className_} 
                        ${animate?style.animate:''}`} style={style_} onClick={onClick_}>
        <img src={red_envelope_down_second} onLoad={onLoad_} className={style.bg} style={style_} />
        <img src={red_envelope_up_second} onLoad={onLoad_} className={`${style.head} ${animateOpening?style.headAni:''}`} style={style_} />
        <img src={btn_chai_second} onLoad={onLoad_} className={`${style.button} ${animateOpening?style.buttonAni:''}`} style={style_} />
      </div>
    )

  return (  //单个默认红包
    detail.isOpen?
        <div className={style.package_open_box} style={style_}>
            <div className={`${String(detail.money).length>4?style.scale_small: null}`}>
                <span className={style.small_text}>￥</span>
                <span className={style.big_text}>{detail.money}</span>
            </div>
        </div>
        :
        Package(animateOpening, onLoad_, onClick_)
      )
}